package secondriver.process.core.source;

import java.awt.image.BufferedImage;
import java.nio.file.Path;
import java.nio.file.Paths;
import secondriver.process.core.ImageProcessUtil;
import secondriver.process.exception.ArgumentInvalidException;
import spark.utils.StringUtils;

/**
 * Author : secondriver
 * Date :  2016/1/7
 */
public class PathSource implements Source<Path> {

    private final Path root;

    public PathSource(String parent) {
        root = Paths.get(parent);
    }

    @Override
    public Path convert(String source) {
        try {
            return Paths.get(root.toString(), source).normalize().toAbsolutePath();
        } catch (Exception e) {
            throw new ArgumentInvalidException(e.getMessage());
        }
    }

    @Override
    public boolean isSupported(String source) {
        if (StringUtils.isNotEmpty(source)) {
            return false;
        }
        Path path = Paths.get(root.toString(), source).normalize().toAbsolutePath();
        return path.isAbsolute() && path.startsWith(root);
    }

    @Override
    public BufferedImage fetch(Path path) {
        return ImageProcessUtil.fetch(path.toFile());
    }

    @Override
    public boolean isRemoteSource() {
        return false;
    }

}